

package com.dog.basics.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.sys.AdminRoleUpdateDto;
import com.dog.basics.bean.dto.admin.sys.AdminSysRoleAddDto;
import com.dog.basics.bean.dto.admin.sys.AdminSysRoleEditDto;
import com.dog.basics.bean.dto.admin.sys.AdminSysRoleFromDto;
import com.dog.basics.bean.model.sys.SysRole;
import com.dog.basics.bean.model.sys.SysRoleMenu;
import com.dog.basics.bean.vo.admin.sys.AdminSysRoleVo;
import com.dog.basics.common.constant.CacheConstants;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.sys.SysRoleMapper;
import com.dog.basics.service.sys.SysRoleMenuService;
import com.dog.basics.service.sys.SysRoleService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guonh
 * @since 2017-10-29
 */
@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMenuService roleMenuService;
    private final MapperFacade mapperFacade;

    /**
     * 通过用户ID，查询角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<AdminSysRoleVo> findRolesByUserId(Long userId) {
        return baseMapper.listRolesByUserId(userId);
    }

    /**
     * 根据角色ID 查询角色列表，注意缓存删除
     *
     * @param roleIdList 角色ID列表
     * @param key        缓存key
     * @return
     */
    @Override
    @Cacheable(value = CacheConstants.ROLE_DETAILS, key = "#key")
    public List<AdminSysRoleVo> findRolesByRoleIds(List<Long> roleIdList, String key) {
        List<SysRole> list = (List<SysRole>) this.listByIds(roleIdList);
        List<AdminSysRoleVo> newList = mapperFacade.mapAsList(list, AdminSysRoleVo.class);
        return newList;
    }

    /**
     * 通过角色ID，删除角色,并清空角色菜单缓存
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeRoleById(Long id) {
        roleMenuService.remove(Wrappers.<SysRoleMenu>update().lambda().eq(SysRoleMenu::getRoleId, id));
        return this.removeById(id);
    }

    /**
     * 根据角色菜单列表
     *
     * @param obj 角色&菜单列表
     * @return
     */
    @Override
    public Boolean updateRoleMenus(AdminRoleUpdateDto obj) {
        SysRole sysRole = baseMapper.selectById(obj.getRoleId());
        return roleMenuService.saveRoleMenus(sysRole.getRoleCode(), obj.getRoleId(), obj.getMenuIds());
    }

    /**
     * @Description: 增加
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAdminObj(AdminSysRoleAddDto obj) {
        SysRole dogNews = new SysRole();
        BeanUtil.copyProperties(obj, dogNews);
        dogNews.setCreateTime(DateUtil.currentSeconds());
        Validator.validateTrue(this.save(dogNews), "common.save");
        return Boolean.TRUE;
    }


    /**
     * @Description: 修改
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editAdminObj(AdminSysRoleEditDto obj) {
        SysRole dogNews = this.getById(obj.getRoleId());
        Validator.validateNotNull(dogNews, "common.noData");
        BeanUtil.copyProperties(obj, dogNews);
        dogNews.setUpdateTime(DateUtil.currentSeconds());
        Validator.validateTrue(this.updateById(dogNews), "common.edit");
        return Boolean.TRUE;
    }

    /**
     * @Description: 分页
     * @Param: status
     * @return: IPage
     * @Author: cy
     * @Date:
     */
    @Override
    public IPage<AdminSysRoleVo> getAdminPageList(PageParam page, AdminSysRoleFromDto obj) {
        IPage iPage = this.page(page, new LambdaQueryWrapper<SysRole>()
                .like(StrUtil.isNotBlank(obj.getRoleCode()), SysRole::getRoleCode, obj.getRoleCode())
                .like(StrUtil.isNotBlank(obj.getRoleName()), SysRole::getRoleName, obj.getRoleName())
                .eq(ObjectUtil.isNotNull(obj.getDsType()), SysRole::getDsType, obj.getDsType())
                .orderByDesc(SysRole::getCreateTime));
        List<SysRole> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            AdminSysRoleVo newVo = new AdminSysRoleVo();
            BeanUtil.copyProperties(e, newVo);
            return newVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 查询详情
     * @Param: status
     * @return: IPage
     * @Author: wph
     * @Date:
     */
    @Override
    public AdminSysRoleVo getObjXq(Long id) {
        SysRole dogNews = this.getById(id);
        Validator.validateNotNull(dogNews, "common.noData");
        AdminSysRoleVo adminSysRoleVo = new AdminSysRoleVo();
        BeanUtil.copyProperties(dogNews, adminSysRoleVo);
        return adminSysRoleVo;
    }
}
